<template>
<div id="amapcontainer">
  正在加载地图...
</div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader';
import {
  AMapConf,
  psConf,
  dsConf,
  polConf,
} from './data2';

export default {
  props: ['center', 'position', 'mkey', 'zoom',
          'region', 'boundaries'],
  data() {
    return {
      AMap: null,
      map: null,
      marker: null,
      val: null,
      point:[],
      district: '',
      districts:'',
      polygons: [],             // 边界
    };
  },
  watch: {
    boundaries(val){
      this.getData(val);      // 如果tab选择,就画区域
      this.val = val;      //判断范围
    },
    position(val){
      this.onZoom(val);
    },
    center(val){
      const { zoom } = this;
      this.map.setZoomAndCenter(zoom, val); // 同时设置地图层级与中心点
    },
  },
  created () {
    this.initMap();
  },
  methods: {
    async initMap () {
      let _this = this;
      const { mkey, zoom, region } = this;
      const conf = {
        ...AMapConf,
        key: mkey,                // 申请好的Web端开发者Key，首次调用 load 时必填
      };
      const mapConf = {
        zoom,                     // 级别
        city: region,
      };
      const AMap = await AMapLoader.load(conf);
      const map = new AMap.Map('amapcontainer', mapConf);
      const marker = new AMap.Marker(
          {
            map: map,
            draggable:true,
            position: [116.566298, 40.014179]
          }
      );
      const placeSearcher = new AMap.PlaceSearch(psConf);
      const districtSearcher = new AMap.DistrictSearch(dsConf);
      this.AMap = AMap;
      this.map = map;
      this.marker = marker;

      map.add(marker);
      map.on('click', this.onClick);

      this.$emit('update:placeSearcher', placeSearcher);
      this.$emit('update:districtSearcher', districtSearcher);
    },
    onClick({ lnglat }) {
      let _this = this;
      this.map.getCity(function(data) {
        _this.districts = data.district;
      });

      const { marker } = this;
      const { lng, lat } = lnglat;
      _this.point = { lng, lat };
      marker.setPosition(lnglat);

      // 判断是否在原来的城市
      this.map.getCity(function(data) {
        _this.districts = data.district;

      AMap.plugin('AMap.Geocoder',function(){//回调函数
        //实例化Geocoder
        let geocoder = new AMap.Geocoder({
          city: ""//城市，默认：“全国”
        });
        let lnglatXY=[lng, lat];//地图上所标点的坐标
        geocoder.getAddress(lnglatXY, function(status, result) {
          if (status === 'complete' && result.info === 'OK') {
            //获得了有效的地址信息:
            _this.district = result.regeocode.addressComponent.district;
              marker.setLabel({
                content:(_this.district==_this.districts)?lnglatXY:'请选择区域内的位置！',
                offset:new AMap.Pixel(20,0)
              });
              console.log(_this.district,_this.districts)
              if(_this.district==_this.districts){
                _this.$emit('update:position', _this.point);
              }
          }else{
            let city = '获取失败';
            //获取地址失败
          }
        });
      })
      });

    //   // this.$emit('reverse', point);
    //   // this.onQuery('丰台区长辛店医院');
    },
    getData(bounds) {
      const { AMap, map, polygons } = this;
      map.remove(polygons);     // 清除之前的边界
      if (bounds) {
        const list = bounds.map(path => new AMap.Polygon({ ...polConf, path }));
        this.polygons = list;
        map.add(list);
        map.setFitView(list);             // 视口自适应
      }
    },
    onZoom(position){
      const { zoom, marker, AMap } = this;
      const { lng, lat } = position;
      if(lng){
        let lnglat = new AMap.LngLat(lng, lat);
        marker.setPosition(lnglat);
        this.map.setZoomAndCenter(zoom, [lng, lat]); // 同时设置地图层级与中心点
        
      }else{
        // 北京
        const lnglat = new AMap.LngLat(116.566298, 40.014179);
        marker.setPosition(lnglat);
        this.map.setZoomAndCenter(zoom, [116.566298, 40.014179]); // 同时设置地图层级与中心点
      }
    },
  },
};
</script>

<style lang="less" module>
:global{
  #amapcontainer{
    width: 100%;
    height: 100%;
  }
}
.amap-marker:first-child .amap-icon img {
  width: 25px;
  height: 34px;
}
.err{
  margin: 0;
  padding: 3px 10px;
  position: absolute;
  color: #f00;
  background: #fff;
  font-size: 14px;
}
</style>
